package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrdersService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartServiceImpl shoppingCartServiceImpl;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public void addOrder(Orders orders) {
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.addressFindOne(addressBookId);
        Long userId = addressBook.getUserId();
        User user = userMapper.selectById(userId);
        String name = user.getName();
        if (name == null) {
            name = addressBook.getConsignee();
        }
        String phone = addressBook.getPhone();
        String consignee = addressBook.getConsignee();
        String address = addressBook.getDetail();
        orders.setUserId(userId);
        orders.setAddress(address);
        orders.setUserName(name);
        orders.setConsignee(consignee);
        orders.setPhone(phone);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        String orderNumber = UUID.randomUUID().toString().substring(10);
        orders.setNumber(orderNumber);
        List<ShoppingCart> shoppingCarts = shoppingCartServiceImpl.cartList(userId);
        BigDecimal amount = new BigDecimal("0");

        for (ShoppingCart shoppingCart : shoppingCarts) {
            BigDecimal number = new BigDecimal(shoppingCart.getNumber() + "");
            BigDecimal multiply = shoppingCart.getAmount().multiply(number);
            amount = amount.add(multiply);
        }
        orders.setStatus(2);
        orders.setAmount(amount);
        ordersMapper.insert(orders);
        Long ordersId = orders.getId();

        shoppingCarts.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(ordersId);
            return orderDetail;
        }).forEach(orderDetailMapper::insert);
        shoppingCartServiceImpl.clearCart(userId);
    }

    @Override
    public Page<OrdersDto> orderPage(Long userId, int page, int pageSize) {
        //根据用户id查询订单表
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userId != null, Orders::getUserId, userId);
        lqw.orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(ordersPage, lqw);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //克隆订单表数据 订单详细表数据 收货地址表数据
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<OrdersDto> ordersDtoList = ordersPage.getRecords().stream().map(orders -> {
            OrdersDto dto = new OrdersDto();
            //根据用户id查询收货地址表
            AddressBook addressBook = addressBookService.addressFindOne(orders.getAddressBookId());
            //克隆属性
            BeanUtils.copyProperties(addressBook, dto);
            BeanUtils.copyProperties(orders, dto);
            //获取订单表id
            Long id = dto.getId();
            LambdaQueryWrapper<OrderDetail> Odlqw = new LambdaQueryWrapper<>();
            Odlqw.eq(OrderDetail::getOrderId, id);
            //查询订点详情表
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(Odlqw);
            dto.setOrderDetails(orderDetails);
            return dto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        return ordersDtoPage;
    }

    public Page<OrdersDto> orderPage(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.eq(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        lqw.gt(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime);
        lqw.lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);
        lqw.orderByDesc(Orders::getOrderTime);

        ordersMapper.selectPage(ordersPage, lqw);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //克隆订单表数据 订单详细表数据 收货地址表数据
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<OrdersDto> ordersDtoList = ordersPage.getRecords().stream().map(orders -> {
            OrdersDto dto = new OrdersDto();
            //根据用户id查询收货地址表
            AddressBook addressBook = addressBookService.addressFindOne(orders.getAddressBookId());
            //克隆属性
            BeanUtils.copyProperties(addressBook, dto);
            BeanUtils.copyProperties(orders, dto);
            //获取订单表id
            Long id = dto.getId();
            LambdaQueryWrapper<OrderDetail> Odlqw = new LambdaQueryWrapper<>();
            Odlqw.eq(OrderDetail::getOrderId, id);
            //查询订点详情表
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(Odlqw);
            dto.setOrderDetails(orderDetails);
            return dto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        return ordersDtoPage;
    }
    //修改订单地址
    @Override
    public void updateStatus(Orders orders) {
        ordersMapper.updateById(orders);
    }
}
